
package com.gitee.jmash.rbac.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import com.gitee.jmash.core.orm.DtoPage;
import com.gitee.jmash.core.orm.DtoTotal;
import com.gitee.jmash.core.orm.jpa.OrderBaseDao;
import com.gitee.jmash.core.orm.jpa.SqlBuilder;
import com.gitee.jmash.core.orm.jpa.TenantEntityManager;
import com.gitee.jmash.rbac.entity.OperationEntity;
import jmash.rbac.protobuf.OperationReq;

/**
 * Operation实体的Dao层（使用JPA实现）.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
public class OperationDao extends OrderBaseDao<OperationEntity, UUID> {

  public OperationDao() {
    super();
  }

  public OperationDao(TenantEntityManager tem) {
    super(tem);
  }

  /** 获取操作编码和操作名称Map */
  public Map<String, String> findCodeNameMap(OperationReq req) {
    List<OperationEntity> list = findListByReq(req);
    return list.stream().collect(Collectors.toMap(OperationEntity::getOperationCode,
        OperationEntity::getOperationName, (key1, key2) -> key1));
  }

  /**
   * 综合查询.
   */
  public List<OperationEntity> findListByReq(OperationReq req) {
    SqlBuilder sqlBuilder = createSql(req);
    String query = sqlBuilder.getQuerySql("select s ");
    return this.findListByParams(query, sqlBuilder.getParams());
  }

  /**
   * 综合查询Page.
   */
  public DtoPage<OperationEntity, DtoTotal> findPageByReq(OperationReq req) {
    SqlBuilder sqlBuilder = createSql(req);
    String query = sqlBuilder.getQuerySql("select s ");
    String totalQuery = sqlBuilder.getTotalSql("select count(s) as totalSize ");
    return this.findDtoPageByParams(req.getCurPage(), req.getPageSize(), query, totalQuery,
        DtoTotal.class, sqlBuilder.getParams());
  }

  /**
   * Create SQL By Req .
   */
  public SqlBuilder createSql(OperationReq req) {
    StringBuilder sql = new StringBuilder(" from OperationEntity s where 1=1  ");
    Map<String, Object> params = new HashMap<String, Object>();

    if (StringUtils.isNotBlank(req.getOperationCode())) {
      sql.append(" and s.operationCode = :operationCode ");
      params.put("operationCode", req.getOperationCode());
    }

    if (StringUtils.isNotBlank(req.getLikeOperationName())) {
      sql.append(" and s.operationName like :operationName ");
      params.put("operationName", "%" + req.getLikeOperationName() + "%");
    }

    String orderSql = " order by s.orderBy asc ";
    if (StringUtils.isNotBlank(req.getOrderName())) {
      orderSql = String.format(" order by %s %s ", req.getOrderName(),
          req.getOrderAsc() ? " asc " : " desc ");
    }

    return SqlBuilder.build().setSql(sql).setParams(params).setOrderSql(orderSql);
  }

}
